const mongoose = require("mongoose");
module.exports = app => {
    const express = require("express")
    const router = express.Router({
        mergeParams: true   //导入父级参数到子级配置
    });
    //快速验证,抛出异常
    const assert = require('http-assert');
    //中间件- 验证用户token返回id
    const auth = require(`../../middle/auth`)(app, ["admin", "user"])
    // APP的数据库
    const APP = require(`../../models/logData`);

    router.post('/', async (req, res) => {
        req.body.logs = [{
            user: req.user.id,
            date: new Date()
        }];
        var date = new Date()
        // var blogs=new Array();
        // req.body.body.map(e=>{
        //     let blog=new APP({
        //         user: req.user.id,
        //         date,
        //         log: e
        //     })
        //       blogs.push(blog);
        // })
        // try{
        //     APP.insertMany(blogs,function(err){
        //         console.log("err",err);
        //       });
        // }catch (e) {
        //     res.send(e)
        //  }
        console.log(req.body.body);
        const msg = await APP.create({
                    user: req.user.id,
                    date,
                    log: req.body.body
                });
        assert(msg, 401, "新建保存失败");
        // res.send(car)
        // const car = await APP.create(arr);
        // console.log(car)
        // assert(car, 401, "新建保存失败");
        res.send({code:200})
    })

    router.put('/', async (req, res) => {
        req.body.logs.push({
            user: req.user.id,
            date: new Date()
        })
        const APP = req.body;
        // delete APP.fID;
        const APPp = await APP.findByIdAndUpdate(req.body._id, APP);
        res.send(APPp)
    })

    router.get('/:id', async (req, res) => {
        const APP = await APP.findById(req.params.id)
        res.send(APP)
    })

    router.delete('/', async (req, res) => {
        // await APP.findByIdAndDelete(req.params.id);
        // await APP.deleteMany()  删除全部
        await APP.remove({user:req.user.id})
        // mongoose.model.remove("APP")
        res.send({ msg: 200 })
    })

    //post获取列表
    router.get('/', async (req, res) => {
        let data = {
            total: 10,
            current: 1,
            size: 10,
            search: "",
        }
        if (req.query.search) {
            data = JSON.parse(req.query.search);
        }


        // let _filter = {
        //     $or: [  // 多字段同时匹配
        //         { "name": { $regex: data.search || '' } },
        //         // { "APPID": { $regex: data.search || '' } }, //  $options: '$i' 忽略大小写
        //     ]
        // }
        // console.log(_filter.$or)
        const { size = 10, current = 1 } = data;
        // let total = await APP.countDocuments()
        let list = [];
        // .populate(["APPegory", "user"])
        await APP.find({user: req.user.id}).populate([{ path: 'logs.user', select: "name" }]).exec((err, result)=>{
            
            result.filter((e)=>{
                var arr = Object.values(e.log);
                // console.log(arr)
                var val = false;
                arr.map(el=>{
                    console.log(el)
                    if (String(el).match(data.search)) {
                        val = true;
                    }
                })                    
                if (val){
                    list.push(e)
                }
            })
            const page = {
                total: list.length,
                size,
                current,
                list: list.slice(size * (current - 1),size * (current))
            };
            res.send(page)
        })
        // .skip(size * (current - 1)).limit(size).sort({ _id: -1 });
        // console.log('list', list)
        // const page = {
        //     total,
        //     size,
        //     current,
        //     list
        // };
        // // console.log('list', list)
        // res.send(page)
    })
    app.use('/admin/api/logData', auth, router);
    //错误函数处理
    app.use(async (err, req, res, next) => {
        console.log(err)
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}